var captchapng = require('captchapng');
var fs = require("fs");

//------------------------工具---------------------------------
//格式化日期
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3),  //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) 
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

String.prototype.format=function(args){
    var result=this;
    if(arguments.length>0){
        if(arguments.length==1&&typeof(args)=='object'){
            for(var key in args){
                if(args[key]!=undefined){
                    var reg=new RegExp("({"+key+"})","g");
                    result=result.replace(reg,args[key]);
                }
            }
        }else{
            for(var i=0;i<arguments.length;i++){
                if(arguments[i]!=undefined){
                    var reg=new RegExp("({)"+i+"(})","g");
                    result=result.replace(reg,arguments[i]);
                }
            }
        }
    }
    return result;
};


exports.get_Time=function(timestamp){
    var newDate = new Date();
    newDate.setTime(timestamp * 1000);
    var y = newDate.getFullYear();
    var m = newDate.getMonth() + 1;
    var d = newDate.getDate();
    return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + newDate.toTimeString().substr(0, 8);
};

var chars=['u','i','o','p','a','s','d','f','g','q','w','e','r','t','A','S','D','F','G','H','J','K','L','Z','y','h','j','c','v','b','n','m',
            'Q','W','E','R','T','Y','U','I','k','l','z','x','O','P','X','C','V','B','N','M'];

exports.generateMixed =function (n){
    var res='';
    for(var i=0;i<n;i++){
        var id=Math.ceil(Math.random()*(chars.length-1));
        res +=chars[id];
    }
    return res;
};

//根据Content-Type的不同，解析post数据
exports.data_parser=function(req,callback){
    req.rawBody = '';
    var json={};
    req.setEncoding('utf8');
    req.on('data',function(chunk){
        req.rawBody+=chunk;
    });
    req.on('end',function(){
        json=JSON.parse(req.rawBody);
        callback(json);
    });
};

exports.send=function(res,ret){
    var str=JSON.stringify(ret);
    res.send(str);
};

exports.getMime=function(fs,path,extname,callback){  /*获取后缀名的方法*/
    // console.log(path.join(__dirname,'../static/json/mime.json'));
    fs.readFile(path.join(__dirname,'../static/json/mime.json'),function(err,data){
        if(err){
            console.log('mime.json文件不存在');
            return false;
        }
        //console.log(data.toString());

        var Mimes=JSON.parse(data.toString());

        var result= Mimes[extname] || 'text/html';

        callback(result)

    });

};

exports.getCode = function(codes_dir) {
    var code =parseInt(Math.random()*90000+10000);
    var p = new captchapng(80,30,code); // width,height,numeric captcha
    p.color(255,255, 255, 255);  // First color: background (red, green, blue, alpha)
    p.color(250, 119, 74, 255); // Second color: paint (red, green, blue, alpha)
    p.color(250, 119, 74, 255);

    var img = p.getBase64();
    var dataBuffer = new Buffer(img,'base64');


    fs.writeFile(codes_dir+"/"+code+".png",dataBuffer, function(err) {
        if(err){
          console.log("code errro！"+err);
        }else{
        //   console.log("保存成功！");
        }
      });
    return code;
};


var getRandom = function(start,end){
    return start+Math.random()*(end-start);
};
